﻿using System;
using System.Diagnostics;
using System.IO;
using System.Net;
using System.Runtime.InteropServices;
using System.Windows.Forms;

namespace FiddlerExUpdate.View
{
    public partial class Update : Form
    {
        private string[] checkUrls = new string[] { };
        //获取本地插件相对路径
        private string savePath;
        private static Process p;
        //private Thread t;

        [DllImport("user32.dll", CharSet = CharSet.Auto)]
        private static extern int SetWindowPos(IntPtr hWnd, int hWndInsertAfter, int x, int y, int Width, int Height, int flags);

        public Update()
        {
            InitializeComponent();
        }

        public Update(string[] args)
        {
            InitializeComponent();
            this.ControlBox = false;
            checkUrls = args;
        }

        private void Update_Load(object sender, EventArgs e)
        {
            try
            {
                if (checkUrls.Length == 1 || checkUrls.Length == 3)
                {
                    if (checkUrls.Length == 3 && checkUrls[1].ToString() != "0") //不等于"0" 即为强制更新
                    {
                        try
                        {
                            //杀掉Fiddler进程
                            Process[] pProcess;
                            pProcess = Process.GetProcesses();
                            for (int i = 1; i <= pProcess.Length - 1; i++)
                            {
                                //MessageBox.Show(pProcess[i].ProcessName);
                                if (pProcess[i].ProcessName == "Fiddler")   //任务管理器应用程序的名
                                {
                                    pProcess[i].Kill();
                                    break;
                                }
                            }
                        }
                        catch (Exception ex)
                        {
                            MessageBox.Show(ex.StackTrace);
                        } 
                    }

                    string newurl = checkUrls[0].Replace('#', ' ');
                    if (checkUrls.Length == 3)
                    {
                        label1.Text = "插件当前有新版本：v" + checkUrls[2];
                    }
                    else
                    {
                        label1.Text = "插件当前有新版本";
                    }
                    
                    //SetWindowPos(this.Handle, -1, 0, 0, 0, 0, 1 | 2); //设置窗口置顶，最后参数也有用1 | 4 p1.MainForm.Handle
                    this.TopMost = true;
                    this.Show();
                    this.Update();
                    savePath = Environment.GetEnvironmentVariable("userprofile") + "\\Documents\\Fiddler2\\" + newurl.Substring(newurl.LastIndexOf('/') + 1);
                    //下载最新插件到本地路径
                    bool result = DownLoadFiles(newurl, savePath);

                    if (result)
                    {
                        if (File.Exists(savePath))
                        {
                            p = new System.Diagnostics.Process();
                            p.StartInfo.FileName = savePath;
                            p.Start();
                        }
                        else
                        {
                            MessageBox.Show(this, savePath + "安装文件不存在！", "FiddlerExUpdate");
                        } 
                    }
                }
                else
                {
                    MessageBox.Show("缺少参数或参数个数不正确，使用方法：FiddlerExUpdate [updateURL]", "FiddlerExUpdate");
                }
                System.Environment.Exit(0);
            }
            catch (Exception ex)
            {
                //MessageBox.Show(this,ex.StackTrace, "FiddlerExUpdate");
                System.Environment.Exit(0);
            }
        }

        public void DownloadFile(string URL, string filename)
        {
            float percent = 0;
            try
            {
                string tempPath = System.IO.Path.GetDirectoryName(filename) + @"\temp";
                System.IO.Directory.CreateDirectory(tempPath);  //创建临时文件目录
                string tempFile = tempPath + @"\" + System.IO.Path.GetFileName(filename) + ".temp"; //临时文件
                if (System.IO.File.Exists(tempFile))
                {
                    System.IO.File.Delete(tempFile);    //存在则删除
                }

                System.Net.FileWebRequest Myrq = (System.Net.FileWebRequest)System.Net.FileWebRequest.Create(URL);
                System.Net.FileWebResponse myrp = (System.Net.FileWebResponse)Myrq.GetResponse();
                long totalBytes = myrp.ContentLength;
                if (progressBar1 != null)
                {
                    progressBar1.Maximum = (int)totalBytes;
                }
                System.IO.Stream st = myrp.GetResponseStream();
                System.IO.Stream so = new System.IO.FileStream(tempFile, System.IO.FileMode.Create);
                long totalDownloadedByte = 0;
                byte[] by = new byte[1024];
                int osize = st.Read(by, 0, (int)by.Length);
                while (osize > 0)
                {
                    totalDownloadedByte = osize + totalDownloadedByte;
                    System.Windows.Forms.Application.DoEvents();
                    so.Write(by, 0, osize);
                    if (progressBar1 != null)
                    {
                        progressBar1.Value = (int)totalDownloadedByte;
                    }
                    osize = st.Read(by, 0, (int)by.Length);

                    percent = (float)totalDownloadedByte / (float)totalBytes * 100;
                    label1.Text = URL.Substring(URL.LastIndexOf('\\') + 1) + " 当前下载进度：" + ((int)percent).ToString() + "%";
                    System.Windows.Forms.Application.DoEvents(); //必须加注这句代码，否则label1将因为循环执行太快而来不及显示信息
                }
                so.Close();
                st.Close();

                progressBar1.Maximum = 100;
                progressBar1.Value = 100;

                if (System.IO.File.Exists(filename))
                {
                    System.IO.File.Delete(filename);    //存在则删除 
                }
                System.IO.File.Move(tempFile, filename);
                if (Directory.Exists(tempPath))
                {
                    Directory.Delete(tempPath, true);
                }
            }
            catch (System.Exception)
            {
                throw;
            }
        }

        public bool DownLoadFiles(string uri, string filefullpath, int size = 1024)
        {
            float percent = 0;
            try
            {
                if (File.Exists(filefullpath))
                {
                    try
                    {
                        File.Delete(filefullpath);
                    }
                    catch (Exception ex)
                    {
                        return false;
                    }
                }
                string fileDirectory = System.IO.Path.GetDirectoryName(filefullpath);
                if (!Directory.Exists(fileDirectory))
                {
                    Directory.CreateDirectory(fileDirectory);
                }
                FileStream fs = new FileStream(filefullpath, FileMode.Create);
                byte[] buffer = new byte[size];
                HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(uri);
                request.Timeout = 10000;
                request.AddRange((int)fs.Length);

                Stream ns = request.GetResponse().GetResponseStream();

                long contentLength = request.GetResponse().ContentLength;
                if (progressBar1 != null)
                {
                    progressBar1.Maximum = (int)contentLength;
                }
                int length = ns.Read(buffer, 0, buffer.Length);
                long totalDownloadedByte = 0;
                while (length > 0)
                {
                    fs.Write(buffer, 0, length);

                    buffer = new byte[size];
                    totalDownloadedByte = length + totalDownloadedByte;
                    System.Windows.Forms.Application.DoEvents();
                    if (progressBar1 != null)
                    {
                        progressBar1.Value = (int)totalDownloadedByte;
                    }
                    length = ns.Read(buffer, 0, buffer.Length);
                    percent = (float)totalDownloadedByte / (float)contentLength * 100;
                    label1.Text = uri.Substring(uri.LastIndexOf('/') + 1) + " 当前下载进度：" + ((int)percent).ToString() + "%";
                    System.Windows.Forms.Application.DoEvents(); //必须加注这句代码，否则label1将因为循环执行太快而来不及显示信息
                }
                fs.Close();
                return true;
            }
            catch (Exception ex)
            {
                MessageBox.Show(this, ex.Message, "FiddlerExUpdate");
                return false;
            }
        }



        private void Update_Shown(object sender, EventArgs e)
        {
        }

        private void Update_FormClosed(object sender, FormClosedEventArgs e)
        {
            this.Dispose();
            this.Close();
            System.Environment.Exit(0);
        }
    }
}
